package channel

import (
	"errors"
	"sync"
)

type Broker struct {
	mutex sync.RWMutex
	chans []chan Msg
}

type Msg struct {
	Content string
}

func (b *Broker) Send(msg Msg) error {
	b.mutex.RLock()
	defer b.mutex.RUnlock()
	for _, ch := range b.chans {
		select {
		case ch <- msg:
		default:
			// 尝试放入队列失败后
			return errors.New("msg queue is full")
		}
	}
	return nil
}

// Subscribe
//
//	@Description: 放入队列
//	@receiver b
//	@param cap
//	@return <-chan
//	@return error
func (b *Broker) Subscribe(cap int) (<-chan Msg, error) {
	res := make(chan Msg, cap)
	b.mutex.Lock()
	defer b.mutex.Unlock()
	b.chans = append(b.chans, res)
	return res, nil
}
